package com.person.leetcode.editor.cn;

import java.util.Arrays;

/**
 * 875.爱吃香蕉的珂珂
 * 2022-06-07 10:28:53
 **/
public class Sequence_0875_KokoEatingBananas {
    public static void main(String[] args) {
        Solution solution = new Sequence_0875_KokoEatingBananas().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int minEatingSpeed(int[] piles, int h) {
            Arrays.sort(piles);
            int len = piles.length;
            int start = (piles[len - 1]-1)/h+1;
            int end = piles[len - 1];
            int mid = end;

            if (1 == len) {
                return (start - 1) / h + 1;
            }

            while (start <= end) {
                mid = (start + end + 1) / 2;
                int time = 0;
                for (int i = 0; i < len; i++) {
                    if (mid >= piles[i]) {
                        time++;
                    } else {
                        int take = (piles[i] - 1) / mid + 1;
                        time += take;
                    }
                }
                if (h < time) {
                    //耗时超了,太慢了,要提速 mid ++
                    if (start == mid){
                        start ++;
                        mid ++;
                    }else{
                        start = mid;
                    }
                } else {
                    //快了,尝试降速 mid --
                    if (end == mid) {
                        end--;
                    } else {
                        end = mid;
                    }
                }
            }
            return mid;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}